Video Thumbnail
2:13
1:23
clock icon Created with Sketch. 2 minutes

Solution: KISS


John Allenor Dizon

from collections import defaultdict def count_fruits(fruits: list[str]) -> dict[str, int]: # your code goes here counter = defaultdict(int) for fruit in fruits: counter[fruit] += 1 return counter

REPLY
Andreas [ArjanCodes Team]

Looks good!

REPLY
Fredrik Magnussen

Ended with the following solution:
```
def count_fruits(fruits: list[str]) -> dict[str, int]:
"""
Count the frequency of each type of fruit in the list.
:param fruits: list[str] - A list of fruits.
:return: dict[str, int] - A dictionary with the fruit names as keys and their counts as values.
"""
fruit_count: dict[str, int] = {}
for unique_fruit in set(fruits):
fruit_count[unique_fruit] = fruits.count(unique_fruit)
return fruit_count
```
Thanks for showing the Counter class

REPLY
Andreas [ArjanCodes Team]

Nice solution! nice use of different data structures to speed thing up also ;)

REPLY
Alexandru Budica

Can't believe I haven't seen the good ol' dict.get() method applied in the comments!

def count_fruits(fruits: list[str]) -> dict[str, int]:
""" Create an empty dictionary. Check if the item exists as a key using the *get* method. If not, create key with 0 as a default value, if it does just add 1 to the value."""

d : dict[str, int] = {}
for item in fruits:
d[item] = d.get(item,0)+1
return d

REPLY
Andreas [ArjanCodes Team]

Nice solution Alexandru!

Can we use this one as an alternative solution in our course repo?

Of course, your code will be acknowledged as a contribution to the course.

If you are interested, contact support@arjancodes.com with your GitHub account name and a link to this conversation

REPLY
Andreas [ArjanCodes Team]

This solution is now added to the GitHub repo under the contributions header in the readme. Thanks again for your contribution!

REPLY
ABDALLAH EL HIDALI

from collections import defaultdict

def count_fruits(fruits: list[str]) -> dict[str, int]:
# your code goes here
counter = defaultdict(int)
for fruit in fruits:
counter[fruit] += 1

return counter

REPLY
Andreas [ArjanCodes Team]

Looks good! Nice work :)

REPLY
Hugi Asgeirsson

You can do it in a single line even without the Counter:

def count_fruits_comprehension(fruits: list[str]) -> dict[str, int]:
return {fruit: len([f for f in fruits if f == fruit]) for fruit in set(fruits)}

REPLY
Andreas [ArjanCodes Team]

Agreed! However, it is less readable in my view because of the nested comprehensions.

REPLY
Show More